package com.lgqz.topsports.activity;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import com.lgqz.topsports.BR;
import com.lgqz.topsports.R;
import com.lgqz.topsports.adapter.ContentCommentRecyclerAdapter;
import com.lgqz.topsports.adapter.RecommendReadRecyclerAdapter;
import com.lgqz.topsports.bean.CommentEntity;
import com.lgqz.topsports.bean.Content;
import com.lgqz.topsports.bean.NewContentEntity;
import com.lgqz.topsports.bean.RecommendReadEntity;
import com.lgqz.topsports.databinding.ActivityTopSportsBinding;
import com.lgqz.topsports.util.HttpService;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TopSportsActivity extends AppCompatActivity implements Callback<NewContentEntity> {
    private ActivityTopSportsBinding binding;
    private long id;
    private RecommendReadRecyclerAdapter adapter;
    private long dashboard_id;
    private HttpService service;
    private ContentCommentRecyclerAdapter commentAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_top_sports);
        adapter = new RecommendReadRecyclerAdapter(new ArrayList(), this);
        commentAdapter = new ContentCommentRecyclerAdapter(new ArrayList(), this);
        binding.commentRecycler.setAdapter(commentAdapter);
        binding.recommendReadRecycler.setAdapter(adapter);
        id = getIntent().getLongExtra("id", 0);
        dashboard_id = getIntent().getLongExtra("dashboard_id", 0);
        Gson gson = initGson();
        //下载webview数据
        service = new Retrofit.Builder()
                .baseUrl("http://api.lifxapi.com/")
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build()
                .create(HttpService.class);
        service.getContent(id).enqueue(this);
        //下载推荐阅读数据
        downLoadRecommendReadData();

        //下载评论数据
        downLoadCommentData();


    }

    private void downLoadRecommendReadData() {
        service.getRecommendReadData(id).enqueue(new Callback<RecommendReadEntity>() {
            @Override
            public void onResponse(Call<RecommendReadEntity> call, Response<RecommendReadEntity> response) {
                List<Content> recs = response.body().getData().getRecs();
                adapter.addAll(recs);

            }

            @Override
            public void onFailure(Call<RecommendReadEntity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(TopSportsActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private void downLoadCommentData() {
        service.getCommentData(dashboard_id).enqueue(new Callback<CommentEntity>() {
            @Override
            public void onResponse(Call<CommentEntity> call, Response<CommentEntity> response) {
                commentAdapter.addAll(response.body().getData().getComments());
            }

            @Override
            public void onFailure(Call<CommentEntity> call, Throwable t) {
                t.printStackTrace();
                Toast.makeText(TopSportsActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();

            }
        });
    }

    private Gson initGson() {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(Date.class, new TypeAdapter<Date>() {
                    private final SimpleDateFormat SDF = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);

                    @Override
                    public void write(JsonWriter out, Date value) throws IOException {
                        if (value == null) {
                            out.nullValue();
                        } else {
                            out.value(SDF.format(value));
                        }
                    }

                    @Override
                    public Date read(JsonReader in) throws IOException {
                        if (in.hasNext()) {
                            String s = in.nextString();
                            try {
                                return SDF.parse(s);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                        }
                        return null;
                    }
                }).create();
        return gson;
    }

    @Override
    public void onResponse(Call<NewContentEntity> call, Response<NewContentEntity> response) {
        String content = response.body().getData().getText_content();
        List<String> images = response.body().getData().getText_images();
        Matcher matcher = Pattern.compile("\\$\\{lx-(\\w+)-?(\\d*)\\}").matcher(content);
        StringBuffer buffer = new StringBuffer("<style>img{max-width:100%}</style>");
        while (matcher.find()) {
            switch (matcher.group(1)) {
                case "br":
                    matcher.appendReplacement(buffer, "<br/>");
                    break;
                case "image":
                    matcher.appendReplacement(buffer, String.format(Locale.getDefault(), "<img src=\"%s\"/>", images.get(Integer.parseInt(matcher.group(2)))));
                    break;
            }
        }
        matcher.appendTail(buffer);
        binding.topSportsWeb.loadData(buffer.toString(), "text/html; charset=utf-8;", "UTF-8");
        binding.topSportsTitle.setText(response.body().getData().getTitle());
        binding.topSportsInfo.setText(response.body().getData().getCreate_time() + "   " + response.body().getData().getUser().getName());
        binding.setVariable(BR.contentData, response.body().getData());
    }

    @Override
    public void onFailure(Call<NewContentEntity> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(this, t.getMessage(), Toast.LENGTH_LONG).show();

    }
}
